#!/usr/bin/env python
"""
PyLink-SR (Python Linked Software Radio System)
(c) Bob Cowdery (G3UKB) 2008

File: jack_connect.py
Date: July 2008

This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

The author can be reached by email at

bob@g3ukb.co.uk

========================================================================
Module Description:

The server side process for jack and controller

"""

#-----------------------------------------------------------------------
# System imports
import logging
import sys
import os
import sys
import subprocess
from time import sleep
import Pyro.core
import Pyro.naming

# Set the PYTHONPATH
# This is a repeat of what goes on in app_main.py
HOME = os.environ['PYLINK_HOME']
sys.path.append(HOME + 'conf')
import config_service as config
config.open_config()
sys.path = sys.path + config.python_path().rsplit(',')

# Application imports
import config_service as config
import logger_service as logger
import jack_invoke
import jack_connect
import pyro_services

#-------------------------------------------------------------------------------
class ServerControl(Pyro.core.ObjBase):
    
    #---------------------------------------------------------------------------
    def __init__(self, logger, pyro_services):
        Pyro.core.ObjBase.__init__(self)
        self.logger = logger
        self.pyro_services = pyro_services
        
    #---------------------------------------------------------------------------
    def close_and_exit(self):
        # Stop Pyro service if started
        self.pyro_services.stop_services()
        # and the daemon if started
        self.pyro_services.stop_daemon()
        
#-------------------------------------------------------------------------------
class PylinkServer():
    
    #---------------------------------------------------------------------------
    def __init__(self):
        logger.init_logger()
        self.logger = logging.getLogger('pylink.logger')
        self.pyro_services = pyro_services.PyroServices()
    
    #---------------------------------------------------------------------------
    def run(self):
        
        # Start Pyro services (we do this for local and remote operation)
        self.pyro_services.start_services()
        # Start the daemon to service remote objects
        daemon = self.pyro_services.start_daemon()
        
        # Connect our server control
        uri=daemon.connect(ServerControl(self.logger, self.pyro_services),"servercontrol")
        
        # Wait for services to start
        sleep(4)
        
        # Start the Controller process
        self.controller = None
        #self.controller = subprocess.Popen(['sudo -E python',config.controller_path()])
        # Note, you must type the pasword into the shell and it won't wait for entry
        self.controller = subprocess.Popen('sudo -E python ' + config.controller_path(), shell=True)
        
        # Connect our jack classes if we are remote
        if config.mode() <> 'standalone':
            # We need to add the Pyro mixin to our classes this side of the fence.
            jack_invoke.JackInvoke.__bases__ += (Pyro.core.ObjBase,)
            jack_connect.JackConnect.__bases__ += (Pyro.core.ObjBase,)
            
            # Expose enough to run the jack master
            uri = daemon.connect(jack_invoke.JackInvoke(),"jackinvoke")
            uri = daemon.connect(jack_connect.JackConnect(),"jackconnect")
        
        # Wait for requests
        self.logger.info('PyLink-SR (Server) running..')
        daemon.requestLoop()
            
        self.logger.info('PyLink-SR (Server) closing..')
        
#--------------------------------------------------------------------------
#
# Start from the command line
#
if __name__ == "__main__":
  app = PylinkServer()
  app.run()